package com.kinon.ceshiaccount.fragment.home;

import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.kinon.ceshiaccount.R;
import com.kinon.ceshiaccount.application.AccountApplication;
import com.kinon.ceshiaccount.bean.urgent.Card;
import com.kinon.ceshiaccount.fragment.BaseFragment;
import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.network.StrCallback;
import com.kinon.ceshiaccount.util.SPManage;
import com.zkteco.android.biometric.core.device.ParameterHelper;
import com.zkteco.android.biometric.core.device.TransportType;
import com.zkteco.android.biometric.core.utils.LogHelper;
import com.zkteco.android.biometric.module.fingerprintreader.FingerprintCaptureListener;
import com.zkteco.android.biometric.module.fingerprintreader.FingerprintSensor;
import com.zkteco.android.biometric.module.fingerprintreader.FingprintFactory;
import com.zkteco.android.biometric.module.fingerprintreader.ZKFingerService;
import com.zkteco.android.biometric.module.fingerprintreader.exception.FingerprintException;

import org.litepal.crud.DataSupport;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by luohao on 2017-10-13.
 * 绑定指纹
 */

public class TieFingerFragment extends BaseFragment implements View.OnClickListener {
    private View mView;
    private EditText et_fCard;
    private Button btn_beginFinger;
    private Button btn_stopFinger;
    private Button btn_enrollFinger;
    private Button btn_identityFinger;
    private Button btn_tieFinger;
    private TextView tv_figerHint;
    private ImageView img_figer;


    private FingerprintSensor mFingerPrintSensor = null;
    private boolean isEnroll = false;
    private boolean isBegin = false;
    private int enrollidx = 0; //录入指纹的次数
    private byte[][] regtemparray = new byte[3][2048];
    private byte[] lastRegTemp = new byte[2048];
    FingerprintCaptureListener fingerListener = new FingerprintCaptureListener() {
        //采集图像成功
        @Override
        public void captureOK(final byte[] bytes) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    tv_hint.setText("采集图像成功"+mFingerPrintSensor.getFakeStatus());
                    Log.e("lh", "captureOK:bytes== " + bytes.length + "\n==" + bytes.toString());
//                    Bitmap bitmapFp = ToolUtils.renderCroppedGreyScaleBitmap
//                            (bytes, mFingerPrintSensor.getImageWidth(),
//                                    mFingerPrintSensor.getImageHeight());
//                    img_figer.setImageBitmap(bitmapFp);
                }
            });
        }

        //采集图像失败
        @Override
        public void captureError(final FingerprintException e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    tv_hint.setText("采集图像失败");
//                    Log.e("lh", "captureError:== "+e.toString() );
                }
            });

        }

        //采集模板成功 fpTemplate指纹模板
        @Override
        public void extractOK(final byte[] fpTemplate) {
            final byte[] tmpBuffer = fpTemplate;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.e("lh", "extractOK:fpTemplate== " + tmpBuffer.length + "\n=="
                            + fpTemplate.toString());
//                    tv_hint.setText("采集模板成功");
                    //录入指纹
                    if (isEnroll) {
                        byte[] bufids = new byte[256];
                        //指纹对比
                        int ret = ZKFingerService.identify(tmpBuffer, bufids, 55, 1);
                        //指纹已存在
                        if (ret > 0) {
                            String strRes[] = new String(bufids).split("\t");
                            tv_figerHint.setText("改指纹已录入,指纹id==" + strRes[0]);
                            enrollidx = 0;
                            return;
                        }
                        //第二次扫指纹 && 与上一次的指纹对比 <23不是同一个手指
                        if (enrollidx > 0 && ZKFingerService
                                .verify(regtemparray[enrollidx - 1], tmpBuffer) <= 0) {
                            tv_figerHint.setText("请使用同一个手指录入");
                            return;
                        }
                        //从索引0开始的2048个数字复制到索引为regtemparray[enrollidx]的位置上
                        System.arraycopy(tmpBuffer, 0, regtemparray[enrollidx], 0, 2048);
                        enrollidx++;
                        //第三次录入
                        if (enrollidx == 3) {
                            byte[] regTemp = new byte[2048];
                            //合并指纹
                            ret = ZKFingerService.merge(regtemparray[0],
                                    regtemparray[1], regtemparray[2], regTemp);
                            Log.e("lu", "ret==" + ret);
                            //合并成功
                            if (ret > 0) {
                                //保存到缓存中
//                                ZKFingerService.save(regTemp,(et_fCard.getText().toString())+"");
                                Log.e("lh", "count== " + ZKFingerService.count());
                                Log.e("lh", "regTemp==" + regTemp);
                                System.arraycopy(regTemp, 0, lastRegTemp, 0, ret);
                                Log.e("lh", "regTemp2==" + regTemp);
                                String strBase64 = Base64
                                        .encodeToString(regTemp, 0, ret, Base64.NO_WRAP);
                                Log.e("lh", "strBase64==" + strBase64);
                                byte[] reg = Base64.decode(strBase64, Base64.NO_WRAP);
                                Log.e("lh", "reg==" + reg.toString());
                                ZKFingerService.save(reg, (et_fCard.getText().toString()) + "");

                                tieFinger(regTemp, ret, et_fCard.getText().toString(), strBase64);
                            } else { //合并失败
                                tv_figerHint.setText("合并指纹模板失败");
                            }
                            isEnroll = false;
//                            enrollidx = 0;
                        } else {
                            tv_figerHint.setText("还需要重复" + (3 - enrollidx) + "次");
                        }
                    } else {//对比指纹
                        byte[] bufids = new byte[256];
                        //返回的对比指纹
                        int ret = ZKFingerService.identify(tmpBuffer, bufids, 55, 1);
                        if (ret > 0) {
                            String strRes[] = new String(bufids).split("\t");
                            tv_figerHint.setText("识别成功：" + "userID="
                                    + strRes[0] + "指纹符合度" + strRes[1] + "%");
                            Log.e("lh", "userID==" + strRes[0]);
                        } else {
                            tv_figerHint.setText("识别失败");
                        }
                    }
                }
            });
        }

        //提取模板失败
        @Override
        public void extractError(final int i) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_figerHint.setText("提取模板失败");
                    Log.e("lh", "extractError:== " + i);
                }
            });
        }
    };

    public TieFingerFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_tiefinger_layout, container, false);
        return mView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext = AccountApplication.getInstance();
        initView();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            clear();
        }
    }

    private void initView() {
        et_fCard = (EditText) mView.findViewById(R.id.et_fCard);
        btn_beginFinger = (Button) mView.findViewById(R.id.btn_beginFinger);
        btn_stopFinger = (Button) mView.findViewById(R.id.btn_stopFinger);
        btn_enrollFinger = (Button) mView.findViewById(R.id.btn_enrollFinger);
        btn_identityFinger = (Button) mView.findViewById(R.id.btn_identityFinger);
        btn_tieFinger = (Button) mView.findViewById(R.id.btn_tieFinger);
        tv_figerHint = (TextView) mView.findViewById(R.id.tv_figerHint);
        img_figer = (ImageView) mView.findViewById(R.id.img_figer);

        hidekey(et_fCard);
        btn_beginFinger.setOnClickListener(this);
        btn_stopFinger.setOnClickListener(this);
        btn_enrollFinger.setOnClickListener(this);
        btn_identityFinger.setOnClickListener(this);
        btn_tieFinger.setOnClickListener(this);

        entryFingerPrint();
    }

    private void getFinger() {
        ArrayList<Card> cards = (ArrayList<Card>) DataSupport.findAll(Card.class, true);
        for (Card card : cards) {
            card.save();
            if (null != card.getFinger() && !"".equals(card.getFinger()) &&
                    null != card.getNo() && !"".equals(card.getNo())) {
                byte[] reg = Base64.decode(card.getFinger(), Base64.NO_WRAP);
                ZKFingerService.save(reg, card.getNo());
                Log.e("lh", "fingersave=====" + card.getFinger());
                Log.e("lh", "getNo=== " + card.getNo());
                Log.e("lh", "reg===\n " + reg);
            }

        }
    }

    private void entryFingerPrint() {
        // Define output log level
        LogHelper.setLevel(Log.ASSERT);
        Map mFingerMap = new HashMap();
        mFingerMap.put(ParameterHelper.PARAM_KEY_VID, 6997);
        mFingerMap.put(ParameterHelper.PARAM_KEY_PID, 288);

        mFingerPrintSensor = FingprintFactory.createFingerprintSensor(mContext,
                TransportType.USB, mFingerMap);
//        mFingerPrint.setFingerprintCaptureListener(3,fingerListener);

    }

    //不弹出键盘
    private void hidekey(EditText et) {
        getActivity().getWindow().setSoftInputMode
                (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        try {
            Class<EditText> cls = EditText.class;
            Method setSoftInputShownOnFocus;
            setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            setSoftInputShownOnFocus.setAccessible(true);
            setSoftInputShownOnFocus.invoke(et, false);
        } catch (Exception e) {

        }

    }

    private void clear() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_beginFinger:
                try {
                    mFingerPrintSensor.open(0);
                    mFingerPrintSensor.setFingerprintCaptureListener(0, fingerListener);
                    mFingerPrintSensor.setFakeFunOn(1);
                    mFingerPrintSensor.startCapture(0);
                    isBegin = true;
//                    ZKFingerService.count();
                    getFinger();
                    Log.e("lh", "count== " + ZKFingerService.count());
                } catch (FingerprintException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_stopFinger:
                if (isBegin) {
                    try {

                        tv_figerHint.setText("停止");
                        mFingerPrintSensor.stopCapture(0);
                        mFingerPrintSensor.close(0);

                    } catch (FingerprintException e) {
                        e.printStackTrace();
//                    tv_figerHint.setText("错误的code:" + e.getErrorCode() +
//                            "错误的msg:" + e.getMessage() + "内部代码:" +
//                            e.getInternalErrorCode());
                    }
                } else {
                    tv_figerHint.setText("已停止");
                }
                break;
            case R.id.btn_enrollFinger:
                if (isBegin) {
                    if ("".equals(et_fCard.getText().toString())) {
                        Toast.makeText(mContext, "请先刷卡",
                                Toast.LENGTH_SHORT).show();
                        isEnroll = false;
                        return;
                    }
                    enrollidx = 0;
                    isEnroll = true;
                    tv_figerHint.setText("您需要成功扫码三次指纹");
                } else {
                    tv_figerHint.setText("请先点击开始");
                }
                break;
            case R.id.btn_identityFinger:
                if (isBegin) {
                    enrollidx = 0;
                    isEnroll = false;
                } else {
                    tv_figerHint.setText("请先点击开始");
                }
                break;
            case R.id.btn_tieFinger:

                break;

        }
    }

    /**
     * 绑卡
     *
     * @param no
     * @param finger
     */
    private void tieFinger(final byte[] regTemp, final int ret, String no, String finger) {
        Call<String> call = HttpManage.getRequestApi().bindFinger
                (SPManage.getInstance().getToken(), no, finger);
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String data) {

                tv_figerHint.setText("录入成功：userId=" + et_fCard.getText().toString());
                et_fCard.setText("");
//                Toast.makeText()
            }

            @Override
            public void onError(int code, String error) {
                tv_figerHint.setText(error);
                et_fCard.setText("");
            }
        });
    }

}
